package com.webserver.http;

import java.io.*;
import java.net.Socket;

/**
 * 响应对象
 * 该类的每一个实例用于表示一个HTTP的响应内容
 * 每个响应由三部分构成:状态行，响应头，响应正文
 */
public class HttpServletResponse {
    //状态行相关信息
    private int statusCode = 200;//状态代码，默认值200
    private String statusReason = "OK";//状态描述

    //响应头相关信息

    //响应正文相关信息
    private File entity;//正文对应的实体文件

    private Socket socket;
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    /**
     * 将当前响应对象内容按照表示的HTTP响应格式发送给客户端
     */
    public void response() throws IOException {
        //1发送状态行
        sendStatusLine();
        //2发送响应头
        sendHeaders();
        //3发送响应正文
        sendContent();
    }

    private void sendStatusLine() throws IOException {
        String line = "HTTP/1.1"+" "+statusCode+" "+statusReason;
        println(line);
    }
    private void sendHeaders() throws IOException {
        //Content-Type: text/html(CRLF)
        String line = "Content-Type: text/html";
        println(line);

        //Content-Length: xxxx(CRLF)
        line = "Content-Length: "+entity.length();
        println(line);

        //单独发送CRLF表示响应头发送完毕了
        println("");
    }
    private void sendContent() throws IOException {
        try(
                FileInputStream fis = new FileInputStream(entity)
        ){
            OutputStream out = socket.getOutputStream();
            int len;//表示每次实际读取到的字节数
            byte[] data = new byte[1024*10];//10kb
            while((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes("ISO8859-1"));
        out.write(13);//发送了一个回车符CR
        out.write(10);//发送了一个换行符LF
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }
}
